package com.ywgt.system.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ywgt.system.mapper.UserMapper;
import com.ywgt.system.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
@Scope(value = "prototype")//多例的
public class WebUserListener extends AnalysisEventListener<User> {

    private static final int BATCH_COUNT = 10;

    private UserMapper userMapper;
    private List<User> users=new ArrayList<>();
    /**
     * 使用spring的时候，使用构造函数传入mapper
     * @param userMapper
     */
    public WebUserListener(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        log.info("存储信息"+user);
        users.add(user);
       if (users.size()>=BATCH_COUNT) {
           userMapper.batchInsert(users);
           users.clear();
       }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("导入信息到数据库成功");
    }
}
